﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace YJKCodeBase.ExcelUtility.ModelLayer
{
	public class Application
	{
		[DllImport("User32.dll", CharSet = CharSet.Auto)]
		private static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

		[DllImport("kernel32.dll")]
		private static extern int OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

		public Workbooks Workbooks
		{
			get
			{
				object property = ExcelUtilityMethod.GetProperty(this.latApplication, "Workbooks");
				return new Workbooks(property);
			}
		}

		public Application()
		{
			try
			{
				this.latApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
				this.hwnd = new IntPtr(this.Hwnd);
				Application.GetWindowThreadProcessId(this.hwnd, out this.pid);
			}
			catch
			{
				throw new ArgumentException("没有安装Microsoft Office Excel。");
			}
			string[] array = new string[]
			{
				"DisplayAlerts",
				"AlertBeforeOverwriting",
				"Visible",
				"Interactive",
				"UserControl",
				"AskToUpdateLinks",
				"AutoFormatAsYouTypeReplaceHyperlinks",
				"DisplayClipboardWindow",
				"DisplayDocumentActionTaskPane",
				"DisplayDocumentInformationPanel",
				"DisplayExcel4Menus",
				"EnableCheckFileExtensions",
				"EnableLargeOperationAlert",
				"MergeInstances",
				"MouseAvailable",
				"ScreenUpdating"
			};
			foreach (string propertyName in array)
			{
				try
				{
					ExcelUtilityMethod.SetProperty(this.latApplication, propertyName, new object[]
					{
						false
					});
				}
				catch (Exception)
				{
				}
			}
		}

		public void Quit()
		{
			ExcelUtilityMethod.UseMethod(this.latApplication, "Quit", null);
			try
			{
				Process processById = Process.GetProcessById(this.pid);
				processById.Kill();
			}
			catch
			{
			}
		}

		private int Hwnd
		{
			get
			{
				return (int)ExcelUtilityMethod.GetProperty(this.latApplication, "Hwnd", null);
			}
		}

		private const int PROCESS_ALL_ACCESS = 2035711;

		private const int PROCESS_VM_READ = 16;

		private const int PROCESS_VM_WRITE = 32;

		private IntPtr hwnd;

		private int pid;

		private object latApplication;
	}
}
